package com.xiaohong.goodsWeb.controller;


import com.xiaohong.goodsWeb.interceptor.TokenRequestInterceptor;
import com.xiaohong.goodsWeb.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import util.ThreadUtils;

import java.io.File;
import java.util.Map;

@RestController
@RequestMapping("/items")
public class PageController {

    @Autowired
    private PageService pageService;

    //静态化页面保存路径
    @Value("${pagepath}")
    private String pagepath;

    /**
     * 生成静态页面
     * @param token 令牌
     * @param selectId_spuid 选中skuId和spuId
     * @return
     */
    @GetMapping("/{token}/{selectId_spuid}.html")
    public ModelAndView createHtml(@PathVariable(name = "selectId_spuid") String selectId_spuid, @PathVariable(name = "token") String token){
        //获取请求头里的token,待会feign时候用
        //TokenRequestInterceptor.token =token;
        ModelAndView modelAndView = new ModelAndView();
        //TokenRequestInterceptor.token = "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJ3ZWIiXSwibmFtZSI6bnVsbCwiaWQiOm51bGwsImV4cCI6MTYwMzM5NjUzOSwiYWdlIjpudWxsLCJhdXRob3JpdGllcyI6WyJhZG1pbiJdLCJqdGkiOiJlNjRmZDdkYy1jMTE0LTQ1MDQtOTRhOC0xMDk2YjBiZWI5ZmYiLCJjbGllbnRfaWQiOiJ4aWFvaG9uZyIsInVzZXJuYW1lIjoieGlhb2hvbmcifQ.qT5rmWN1HdJtYqlZCJewwI5H7KxgMRpRWaVax5tjQszvhQdvgc-Be-LTNbJXOzD7VhTdcVTAycfk-MkJ2pAkwmrtW9QWALMXSIkRiCMf7GlHmfZA1T5V4paqTd1dBSS5aJoMLu_Ps5Z2o9Q-DTDAa0-e39gdsE759zNKtMo1BKBtq4icrzC1FXMI1Y_THPvA29Jcj3HlUIECCego1LlnxrwFdGZnbwbLH8Z6Bfl0IlhHZto527qfBSzCSqlTR6GV5BRXFS1Bfwx2Uq242aUN68t4qAAmq_9XcKcfZ-cbxz7KDfGWlliTMSZGiYU4l97onVBYa-Y76newTuV-x0cqYQ";
        // 字符串分离获取spuId和选中skuId
        String[] s = selectId_spuid.split("_");
        String selectId = s[0];
        String spuId = s[1];
        try {
            File file = new File(pagepath+"/"+selectId_spuid+".html");
            if(!file.exists()){
                // 新建线程静态化页面
                ThreadUtils.execute(()->pageService.createPageHtml(spuId,token,selectId,selectId_spuid));
            }
//            return new Result(true,StatusCode.OK,"生成静态页面成功");
//            Thread.sleep(5000);
            Map<String, Object> map = pageService.buildDataModel(spuId,token,selectId);
            modelAndView.addAllObjects(map);
            modelAndView.setViewName("item");
            return modelAndView;
        }catch (Exception e){
//            return new Result(false,StatusCode.REMOTEERROR,"生成静态页面失败");
            e.printStackTrace();
            return null;
        }

    }
}
